package com.sky.wsp.license.utils;

import sun.misc.HexDumpEncoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.*;

/**
 * @author wangshaopeng@talkweb.com.cn
 * @desccription 加解密工具类
 * @date 2024/6/24
 */
public class CipherUtil {
    /**
     * RSA非对称加密
     *
     * @param plainText  要加密的字符串数据
     * @param privateKey 私钥
     * @return
     */
    public static String rsaEncrypt(String plainText, PrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            cipher.update(plainText.getBytes(StandardCharsets.UTF_8));
            byte[] cipherData = cipher.doFinal();
            String s = DatatypeConverter.printHexBinary(cipherData);
            String encoded = new HexDumpEncoder().encode(cipherData);
            System.out.printf("加密值：%n%s%n", encoded);
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * RSA非对称解密
     *
     * @param hexText   加密后数据的十六进制字符串
     * @param publicKey 公钥
     * @return
     */
    public static String rsaDecrypt(String hexText, PublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            cipher.update(DatatypeConverter.parseHexBinary(hexText));
            byte[] cipherData = cipher.doFinal();
            String decrypt = new String(cipherData, StandardCharsets.UTF_8);
            System.out.printf("解密值： %s%n", decrypt);
            return decrypt;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        }
    }
}
